package com.my.lock.test;

import cn.hutool.core.util.IdUtil;
import com.my.core.domain.exception.ServiceException;
import com.my.lock.redis.LockKeyConstan;
import com.my.lock.redis.RedisLock;
import com.my.lock.redis.RedissonClientDistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author timo 2021/4/15
 */
@Controller
@Slf4j
public class IndexController {
    //两种方式
    @Autowired
    RedisLock redisLock;
    @Resource
    private RedissonClient redissonClient;
    int count = 0;

    @RequestMapping("/index")
    @ResponseBody
    public String index() throws InterruptedException {
        /*第一种方式 推荐*/
        String serId = "";//业务id
        RedissonClientDistributedLock lock = new RedissonClientDistributedLock(redissonClient, LockKeyConstan.LOCK_WANGGE_TEAIN_APPLY+ serId);
        try {
            //获取锁
            if (lock.getLock()){

            }else {
                log.error("获取lock 失败!");
                throw new ServiceException("xxxx，请重试!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.release();
        }

        /*第二种*/
        int clientcount =1000;
        CountDownLatch countDownLatch = new CountDownLatch(clientcount);

        ExecutorService executorService = Executors.newFixedThreadPool(clientcount);
        long start = System.currentTimeMillis();
        for (int i = 0;i<clientcount;i++){
            executorService.execute(() -> {
                //通过Snowflake算法获取唯一的ID字符串
                String id = IdUtil.randomUUID();
                try {
                    redisLock.lock(id);
                    count++;
                }finally {
                    redisLock.unlock(id);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        log.info("执行线程数:{},总耗时:{},count数为:{}",clientcount,end-start,count);
        return "Hello";
    }
}

